<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="报销时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="报销金额" prop="reimAmount">
        <el-input
          v-model="queryParams.reimAmount"
          placeholder="请输入报销金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报销部门">
        <el-cascader
          v-model="queryParams.params.reimDept"
          ref="cascaderDept"
          :options="this.deptTree"
          :props="{ expandTrigger: 'hover', value: 'id' }"
          ></el-cascader>
      </el-form-item>
      <!-- <el-form-item label="报销类型" prop="reimType">
        <el-input
          v-model="queryParams.reimType"
          placeholder="请输入报销类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['daily:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['daily:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['daily:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip class="item" effect="dark" content="默认统计所有未报销记录" placement="top-start">
          <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleStat"
          v-hasPermi="['daily:record:stat']"
        >统计</el-button>
        </el-tooltip>
      </el-col>
      <!-- <el-col :span="1.5">
        <span>是否统计已报销记录</span>
        <el-tooltip class="item" effect="dark" content="打开后可统计已报销记录" placement="top-start">
          <el-switch
            v-model="queryParams.params.isFinishStat"
            active-color="#13ce66">
          </el-switch>
        </el-tooltip>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="selectable"/>
      <el-table-column label="报销时间" align="center" prop="reimDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reimDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报销金额" align="center" prop="reimAmount" />
      <el-table-column label="报销类型" align="center" prop="reimType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.reim_type" :value="scope.row.reimType"/>
        </template>
      </el-table-column>
      <el-table-column label="报销人" align="center" prop="reimSpender" :formatter = "spenderFormat">
        <!-- <template slot-scope="scope">
          <dict-tag :options="this.userMap" :value="scope.row.reimSpender"/>
        </template> -->
      </el-table-column>
      <!-- <el-table-column label="报销发票" align="center" prop="reimInvoice" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.reimInvoice" :width="50" :height="50"/>
        </template>
      </el-table-column> -->
      <el-table-column label="报销支付记录" align="center" prop="reimImg" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.reimImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="参与人" align="center" prop="reimUser" />
      <el-table-column label="报销情况" align="center" prop="exportId">
        <template slot-scope="scope">
          <el-tag
          :type="scope.row.exportId === '' ? 'primary' : 'success'"
          disable-transitions>{{ scope.row.exportId === '' ? '未报销' : '已报销' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['daily:record:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['daily:record:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报销记录（个人）对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="报销时间" prop="reimDate">
          <el-date-picker clearable
            v-model="form.reimDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择报销时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报销金额" prop="reimAmount">
          <el-input v-model="form.reimAmount" placeholder="请输入报销金额" style="width: 220px;"/>
        </el-form-item>
        <el-form-item label="报销类型" prop="reimType">
          <el-select v-model="form.reimType" placeholder="请选择报销类型">
            <el-option
              v-for="dict in dict.type.reim_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报销人" prop="reimSpender">
          <el-cascader
            v-model="form.reimSpender"
            ref="cascaderSpender"
            :options="this.userTree"
            :props="{ expandTrigger: 'hover' }"
            ></el-cascader>
        </el-form-item>
        <!-- <el-form-item label="报销发票">
          <image-upload v-model="form.reimInvoice"/>
        </el-form-item> -->
        <el-form-item label="支付记录">
          <image-upload v-model="form.reimImg"/>
        </el-form-item>
        <el-form-item label="参与人" prop="reimUser">
          <el-input v-model="form.reimUser" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <span style="float: left;font-size: small;">继续填写下一个</span>
        <el-switch
          style="float: left;"
          v-model="fillNext"
          active-value=1
          inactive-value=0>
        </el-switch>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openTable" width="800px" append-to-body>
      <!-- <el-form :inline="true">
        <el-form-item>
          <el-date-picker
            v-model="dateRangeStat"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-cascader
            v-model="spenderDept"
            ref="cascaderDept"
            :options="this.deptTree"
            :props="{ expandTrigger: 'hover' }"
            ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleStat">搜索</el-button>
        </el-form-item>
      </el-form> -->
      <el-table
        :data="tableData"
        style="width: 100%">
        <el-table-column
          label="姓名"
          prop="spender">
        </el-table-column>
        <el-table-column
          label="报销次数"
          prop="recordCount">
        </el-table-column>
        <el-table-column
          label="餐费"
          prop="mealAmount">
        </el-table-column>
        <el-table-column
          label="交通费"
          prop="trafficAmount">
        </el-table-column>
        <el-table-column
          label="无截图记录数"
          prop="missImg">
        </el-table-column>
        <el-table-column
          label="合计"
          prop="totalAmount">
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportImgs">导出支付记录</el-button>
        <el-button type="primary" @click="exportCover">导出报销封面</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecord, getRecord, delRecord, addRecord, updateRecord, confirmStat, statRecord, imgsRecord, coverRecord, completeRecord } from "@/api/reim/daily/record";
import { treeUser, mapUser } from "@/api/system/user";
import { treeselect } from '@/api/system/dept'
const axios = require('axios');
export default {
  name: "Record",
  dicts: ['reim_type', 'reim_batch'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 树状结构
      userTree: [],
      userMap: {},
      deptTree: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 是否填写下一个
      fillNext: 0,
      // 报销记录（个人）表格数据
      recordList: [],
      // 日期范围
      dateRange: [],
      dateRangeStat: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openTable: false,
      // 统计 部门筛选
      spenderDept: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reimDate: null,
        reimAmount: null,
        reimType: null,
        reimBatch: null,
        reimMode: null,
        reimInvoice: null,
        reimImg: null,
        reimUser: null,
        reimSpender: null,
        params: {
          reimDept: null,
          isFinishStat: false
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        reimDate: [
          { required: true, message: "报销时间不能为空", trigger: "blur" }
        ],
        reimAmount: [
          { required: true, message: "报销金额不能为空", trigger: "blur" }
        ],
        reimType: [
          { required: true, message: "报销类型不能为空", trigger: "change" }
        ],
        reimSpender: [
          { required: true, message: "报销人不能为空", trigger: "change" }
        ],
      },
      tableData: [],
      pickerOptions: {
          disabledDate: (time) => {
                let beginDate = new Date(this.startTime)
                let endDate = new Date(this.endTime)
                return time.getTime() > endDate.getTime() || time.getTime() < beginDate.getTime()
          },
          shortcuts: [
          {
            text: '昨日',
            onClick(picker) {
              const end = new Date();
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
              end.setHours(23);end.setMinutes(59);end.setSeconds(59);
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '今日',
            onClick(picker) {
              const end = new Date();
              end.setTime(end.getTime());
              end.setHours(end.getHours());
              end.setMinutes(end.getMinutes());
              end.setSeconds(end.getSeconds());
              const start = new Date();
              start.setTime(start.getTime());
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              end.setHours(23);end.setMinutes(59);end.setSeconds(59);
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近30天',
            onClick(picker) {
              const end = new Date();
              end.setHours(23);end.setMinutes(59);end.setSeconds(59);
              const start = new Date();
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 29);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近90天',
            onClick(picker) {
              const end = new Date();
              end.setHours(23);end.setMinutes(59);end.setSeconds(59);
              const start = new Date();
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              end.setHours(23);end.setMinutes(59);end.setSeconds(59);
              const start = new Date();
              start.setHours(0);start.setMinutes(0);start.setSeconds(0);
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit('pick', [start, end]);
            }
          },
          ],
      },
    };
  },
  created() {
    // this.defaultDate();
    this.getList();
    treeUser().then(response => {
      this.userTree = response
    });
    mapUser().then(response => {
      this.userMap = response;
    });
    treeselect().then(response => {
      this.deptTree = response.data
    });
  },
  methods: {
    /** 查询报销记录（个人）列表 */
    getList() {
      this.loading = true;
      listRecord(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
        this.ids = response.rows.map(item => item.reimId);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openTable = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        reimId: null,
        reimDate: null,
        reimAmount: null,
        reimType: null,
        reimMode: null,
        reimInvoice: null,
        reimImg: null,
        reimUser: null,
        remark: null,
        reimSpender: null,
        createBy: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.params.reimDept != undefined) {
        this.queryParams.params.reimDept = this.$refs['cascaderDept'].getCheckedNodes()[0].value;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.params.reimDept = undefined;
      // this.$refs['cascaderDept'].getCheckedNodes()[0].value = null;
      this.queryParams.reimAmount = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reimId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.handleAddFill();
    },
    // 点击新增按钮进行数据填充
    handleAddFill() {
      // 自动填充报销人
      this.form.reimSpender = this.$store.state.user.id;
      // 报销类型及时间
      this.form.reimType = 'eat';
      this.form.reimDate = new Date();
      this.title = "添加报销记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const reimId = row.reimId || this.ids
      getRecord(reimId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改报销记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.reimSpender = this.$refs['cascaderSpender'].getCheckedNodes()[0].value;
        if (valid) {
          if (this.form.reimId != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              if (this.fillNext == 1) {
                this.getList();
                this.reset();
                this.handleAddFill();
              } else {
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const reimIds = row.reimId || this.ids;
      this.$modal.confirm('是否确认删除报销记录（个人）编号为"' + reimIds + '"的数据项？').then(function() {
        return delRecord(reimIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 统计按钮操作 */
    async handleStat(row) {
      this.title = "报销统计";
      // this.ids = []
      const reimIds = this.ids;
      let flag;
      // await confirmStat(this.addDateRange(reimIds, this.spenderDept, this.dateRange)).then(async response => {
      await confirmStat(reimIds).then(async response => {
        // this.ids = response.reimIds;
        flag = response.flag;
        if (flag == false) {
          await this.$modal.confirm(response.msg).then(() => {
            flag = true;
          });
        }
      });
      if (flag == true) {
        statRecord(this.ids).then(response => {
          this.openTable = true;
          this.tableData = response.rows;
        });
      }
    },
    // 导出支付记录word
    async exportImgs() {
      if(this.ids.length == 0 || this.tableData.length == 0) {
        this.$modal.msg("无记录");
        return;
      } 
      // await this.$modal.confirm("是否将这些记录标记为报销完成（无法再次进行报销）并导出报销单？").then(() => {
        imgsRecord(this.ids).then(res=>{
          const data = res
          var binaryData = [];
          binaryData.push(data);
          let url = window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"}))   // 将二进制文件转化为可访问的url
          var a = document.createElement('a')  
          document.body.appendChild(a)
          a.href = url
          a.download = '报销-支付记录.docx'
          a.click()   // 模拟点击下载
          window.URL.revokeObjectURL(url)
          // this.openTable = false;
        });
        // completeRecord(this.ids).then(response => {
        //   this.openTable = false;
        //   this.getList();
        // });
      // });
      // this.exportCover();
      // this.ids = [];
    },
    // 导出报销封面excel
    async exportCover() {
      await this.$modal.confirm("是否将这些记录标记为报销完成（无法再次进行报销）并导出报销单？").then(() => {
        coverRecord(this.ids).then(res=>{
          const data = res
          var binaryData = [];
          binaryData.push(data);
          let url = window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"}))   // 将二进制文件转化为可访问的url
          var a = document.createElement('a')  
          document.body.appendChild(a)
          a.href = url
          a.download = '报销-封面.xlsx'
          a.click()   // 模拟点击下载
          window.URL.revokeObjectURL(url)
          // this.openTable = false;
        });
        // completeRecord(this.ids).then(response => {
        //   this.openTable = false;
        //   this.ids = [];
        //   this.getList();
        // });
      });
      this.openTable = false;
      this.ids = [];
    },
    //设置默认日期
    defaultDate(){
        //获取新的时间
        let date = new Date()
        //获取当前时间的年份转为字符串
        let year = date.getFullYear().toString()
        //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
        let month = date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1).toString():(date.getMonth()+1).toString()  //'04'
        //获取天，判断是否小于10，如果是在字符串前面拼接'0'
        let da = date.getDate() < 10 ? '0'+date.getDate().toString():date.getDate().toString()  //'12'
        //字符串拼接，开始时间，结束时间
        let end = year + '-' + month + '-' + da
        let beg = year + '-' + month + '-01'
        this.dateRange = [beg,end] //将值设置给插件绑定的数据
    },
    // 报销人字典映射
    spenderFormat(row, column) {
      let reimSpender = row.reimSpender;
      return this.userMap[reimSpender];
    },
    selectable(row, index) {
        if(row.exportId == ''){
          return true;
        }
    },
  }
};
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 200px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>